﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Primitives;

namespace EssentialWebFramework.Common.Middlewares
{
    /// <summary>
    /// 失效的 token 过滤器（用于手动退出的用户，仅适用于单机部署）
    /// </summary>
    public class InvalidTokenFilterMiddleware
    {
        /// <summary>
        /// 缓存 TAG
        /// </summary>
        public const string INVALID_TOKEN_CACHE_TAG = "InvalidToken";

        /// <summary>
        /// 组件缓存
        /// </summary>
        private readonly CacheForComponent _cache;

        /// <summary>
        /// next
        /// </summary>
        private RequestDelegate _next;

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="next"></param>
        /// <param name="distributedCache"></param>
        public InvalidTokenFilterMiddleware(RequestDelegate next, IDistributedCache distributedCache)
        {
            _next = next;
            _cache = new CacheForComponent(INVALID_TOKEN_CACHE_TAG, distributedCache);
        }

        /// <summary>
        /// Invoke
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            /* 黑名单，仅针对有 token 但失效的（如退出登录），其它情况交由后续的 jwt 认证处理 */             

            bool isExist = context.Request.Headers.TryGetValue("Authorization", out StringValues tmpValues);
            if (isExist && tmpValues.Any())
            {
                string token = tmpValues.First();
                string key = token.Substring(token.Length - 10); ;
                bool isCacheExist = _cache.TryGetCacheValue(key, out string _);
                if (isCacheExist)
                {
                    context.Response.StatusCode = 401;
                    context.Response.Body.Close();
                    return;
                }
            }            

            await _next(context);
        }
    }
}
